/**
 *
 */
package com.rf.richfitwheel.admin.sys.controller;

import com.rf.richfitwheel.admin.annotation.ModifyAnnotaionFactory;
import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.iam.service.PortalUserService;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.*;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.UuidUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * @author hushouquan
 */
@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/user")
public class SysUserController {

    private static Logger log = LoggerFactory.getLogger(SysUserController.class);

    /**saveUserInfo
     * 正则表达式-强密码-【必填字母数字及特殊字符，且以字母开头，8位以上】
     */
    public static final String REGEX_PASSWORD_STRONG = "^(?![0-9]+$)(?![^0-9]+$)(?![a-zA-Z]+$)(?![^a-zA-Z]+$)(?![a-zA-Z0-9]+$)[a-zA-Z0-9\\S]{8,}$";

    @Resource(name = "sysUserService")
    private SysUserService sysUserService;

    @Resource(name = "sysUserRoleService")
    private SysUserRoleService sysUserRoleService;

    @Resource(name = "sysUserMngOrgService")
    private SysUserMngOrgService sysUserMngOrgService;

    @Resource(name = "sysUserStationService")
    private SysUserStationService sysUserStationService;

    @Resource(name = "orgService")
    private OrgService orgService;
    @Resource(name = "sysRoleService")
    private SysRoleService sysRoleService;
    @Resource(name = "stationService")
    private StationService stationService;
    @Resource(name = "sysUserAuthDataService")
    private SysUserAuthDataService sysUserAuthDataService;
    @Autowired
    private PortalUserService portalUserService;
    
    @GetMapping("/list")
//	@RequiresPermissions("sys:role:list")
    public R list(@RequestParam Map<String, Object> params) {
        //如果不是超级管理员，则只查询自己租户的用户列表
        UserVO userVO = UserUtil.getUser();
        PageUtils page = sysUserService.queryPage(params, userVO);

        return R.ok().put("page", page);
    }

    /**
     * 修改登录用户密码，用户自行修改。
     */
    @UserOperateLog(module = "系统功能", methods = "password", description = "修改密码", functionNo = "101035")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {

        UserVO userVO = UserUtil.getUser();
        ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "password", "bussid", userVO.getId(), form.getClass());
        if (!form.getNewPassword().matches(REGEX_PASSWORD_STRONG)) {
            return R.error(886, "密码必需含字母数字及特殊字符，且以字母开头，8位以上");
        }
        //更新密码
        boolean flag = sysUserService.updatePassword(userVO, form.getPassword(), form.getNewPassword());
        if (!flag) {
            return R.error(888, "原密码不正确");
        }

        return R.ok();
    }

    /**
     *
     * <p>Title: 系统管理员给用户重置密码</p>
     * <p>Description: </p>
     * @param userId
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "resetPassword", description = "重置密码")
    @GetMapping("/resetPassword/{userId}")
    public R resetPassword(@PathVariable("userId") String userId) {
        try {
            if (userId.equals(UserUtil.getUser().getId())) {
                return R.error("不要重置自己的密码！");
            }
            String password = sysUserService.resetPassword(userId, UserUtil.getUser());
            return R.ok().put("random", password);
        } catch (Exception e) {
            log.error("重置密码失败", e);
            return R.error("重置密码失败！");
        }
    }

    /**
     * 新增用户
     * @param param
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "save", description = "新增用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:add")
    public R save(@RequestBody Map<String, Object> param) {
        try {
            UserVO userVO = UserUtil.getUser();
            User user = (User) JSONObject.toBean(JSONObject.fromObject(param.get("user")), User.class);
            JSONArray mngOrgArr = JSONArray.fromObject(param.get("mngOrgs"));

			/*String tenantId = "";
			if(userOp.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
				tenantId = user.getTenantId();
			} else {
				tenantId = userOp.getTenantId();
			}*/
            boolean ckUserName = sysUserService.checkUserName(user.getUsername(), "");
            if (ckUserName) {
                return R.error("用户名已被占用");
            }
            ckUserName = sysUserService.checkUserName(user.getUsername(), "1");
            if (ckUserName) {
                return R.error("用户名已被占用");
            }
//	        user.setTenantId(tenantId);
            user.setCreateUserId(userVO.getId());
            sysUserService.save(user, mngOrgArr);
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("新增用户失败", e);
            return R.error("新增用户失败");
        }
    }

    /**
     * 修改用户信息
     * @param param
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "update", description = "修改用户")
    @PostMapping("/update")
    @RequiresPermissions("sys:user:edit")
    public R update(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        try {
            UserVO userVO = UserUtil.getUser();
            User user = (User) JSONObject.toBean(JSONObject.fromObject(param.get("user")), User.class);
            user.setLastChangeder(userVO.getId());
            JSONArray mngOrgArr = JSONArray.fromObject(param.get("mngOrgs"));
            String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型，如果有值就查对应模块菜单
            sysUserService.update(user, mngOrgArr, moduleType);
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改用户失败", e);
            return R.error("修改用户失败");
        }
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/info/{userId}")
//  @RequiresPermissions("sys:user:info") shiro权限校验
    public R info(@PathVariable("userId") String userId, HttpServletRequest request) {
        User user = sysUserService.selectById(userId);
        String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型，如果有值就查对应模块菜单
        List<UserMngOrgVo> userMngOrgVos = new ArrayList<>();
        List<UserMngOrg> userMngOrgs = sysUserMngOrgService.getListByUserId(userId);
        for (UserMngOrg userMngOrg : userMngOrgs) {
            UserMngOrgVo userMngOrgVo = new UserMngOrgVo();
            OrgVO orgVO = orgService.getOrgAndParentOrgByOrgId(userMngOrg.getOrgId());
            userMngOrgVo.setOrgId(orgVO.getId());
            userMngOrgVo.setOrgCode(orgVO.getOrgCode());
            userMngOrgVo.setOrgName(orgVO.getOrgName());
            userMngOrgVo.setOrgRank(orgVO.getOrgRank());
            userMngOrgVo.setParentId(orgVO.getParentOrg() == null ? null : orgVO.getParentOrg().getId());
            userMngOrgVo.setParentName(orgVO.getParentOrg() == null ? null : orgVO.getParentOrg().getOrgName());
            userMngOrgVo.setDefaultState(userMngOrg.getDefaultState());
            List<UserRole> userRoles = sysUserRoleService.getListByUserIdAndOrgId(userId, userMngOrg.getOrgId(), moduleType);
            List<List<String>> roleDatas = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                Role role = sysRoleService.selectById(userRole.getRoleId());
                if (!ObjectUtils.isEmpty(role)) {
                    List<String> roleData = new ArrayList<>();
                    roleData.add(role.getModuleType());
                    roleData.add(role.getId());
                    roleDatas.add(roleData);
                }
            }
            userMngOrgVo.setRoleDatas(roleDatas);
            List<UserStation> userStations = sysUserStationService.getListByUserIdAndOrgId(userId, userMngOrg.getOrgId(), moduleType);
            List<List<String>> stationDatas = new ArrayList<>();
            for (UserStation userStation : userStations) {
                Station station = stationService.selectById(userStation.getStationId());
                if (!ObjectUtils.isEmpty(station)) {
                    List<String> stationData = new ArrayList<>();
                    stationData.add(station.getModuleType());
                    stationData.add(station.getId());
                    stationDatas.add(stationData);
                }
            }
            userMngOrgVo.setStationDatas(stationDatas);

            List<UserAuthData> userAuthDatas = sysUserAuthDataService.getListByUserIdAndOrgId(userId, userMngOrg.getOrgId(), moduleType);
            List<Map<String, String>> authDatas = new ArrayList<>();
            for (UserAuthData userAuthData : userAuthDatas) {

                Map<String, String> authData = new HashMap<>();
                authData.put("moduleType", userAuthData.getModuleType());
                authData.put("dataLevel", userAuthData.getDataLevel());
                if (userAuthData.getModuleType().equals("all")) {
                    authData.put("disabled", "1");
                } else {
                    authData.put("disabled", "0");
                }
                authDatas.add(authData);
            }
            userMngOrgVo.setAuthDatas(authDatas);
            userMngOrgVos.add(userMngOrgVo);
        }
        return R.ok().put("user", user).put("userMngOrgVos", userMngOrgVos);
    }

    /**
     * 获取用户信息
     * @param stationIds
     * @return
     */
    @GetMapping("/getUserListByStationIds/{stationIds}")
//  @RequiresPermissions("sys:user:info") shiro权限校验
    public List<User> getAllUserByStationIds(@PathVariable("stationIds") String stationIds) {
        List<User> users = sysUserService.getAllUserByStationIds(stationIds);
        return users;
    }

    @UserOperateLog(module = "系统功能", methods = "delete", description = "删除用户")
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody String[] userIds) {
        UserVO userVO = UserUtil.getUser();
        if (ArrayUtils.contains(userIds, "1")) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, userVO.getId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }

    /**
     * 获取用户岗位信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserStationList/{userId}")
//  @RequiresPermissions("sys:user:info") shiro权限校验
    public R getUserStationList(@PathVariable("userId") String userId) {
        List<UserStation> userStations = sysUserService.getUserStationList(userId);
        return R.ok().put("stationList", userStations);
    }

    /**
     * <p>Title: 设置用户岗位</p>
     * <p>Description: 仅设置用户岗位 </p>
     *
     * @param params {userId：用户id，stationIdList：岗位id数组}
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "setUserStation", description = "设置用户岗位", functionNo = "101041")
    @PostMapping("/setUserStation")
    public R setUserStation(@RequestBody Map<String, Object> params) {
        try {
            String userId = params.get("userId") == null ? null : params.get("userId").toString();
            if (userId == null) {
                return R.error(1, "请传入用户ID");
            }
            JSONArray jarr = JSONArray.fromObject(params.get("stationList"));
            List<UserStation> stationList = new ArrayList<UserStation>();
            for (Object obj : jarr) {
                JSONObject jobj = JSONObject.fromObject(JSONObject.fromObject(obj).get("data"));
                UserStation us = new UserStation();
                us.setId(UuidUtil.get32UUID());
                us.setStationId(jobj.getString("id"));
                us.setUserId(userId);
                stationList.add(us);
            }
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "setUserStation", "bussid", userId, Map.class);
            UserVO userVO = UserUtil.getUser();
            sysUserService.setUserStation(userId, stationList, userVO);
            return R.ok();
        } catch (Exception e) {
            log.error("设置用户岗位失败", e);
            return R.error(1, "设置用户岗位失败");
        }
    }

    /**
     * 查找所有的用户
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/getAllUserByTenantId")
    public List<User> getAllUserByTenantId() throws Exception {
        UserVO userVO = UserUtil.getUser();
        List<User> userList = sysUserService.getAllUserByTenantId(userVO.getTenantId());
        return userList;
    }

    /**
     * 根据orgCode查询没同步的用户（来自账户系统的数据）,分页
     * @param params
     * @return
     */
    @GetMapping("/listTemp")
//	@RequiresPermissions("sys:role:list")
    public R listTemp(@RequestParam Map<String, Object> params) {
        //如果不是超级管理员，则只查询自己租户的用户列表
        UserVO userVO = UserUtil.getUser();
        PageUtils page = sysUserService.queryPageListTemp(params, userVO);
        return R.ok().put("page", page);
    }

    @UserOperateLog(module = "系统功能", methods = "importUsersFromAccount", description = "同步账户数据")
    @PostMapping("/importUsersFromAccount")
    public R importUsersFromAccount(@RequestBody Map param) {
        try {
            sysUserService.importUsersFromAccount(param, UserUtil.getUser());
            return R.ok();
        } catch (Exception e) {
            log.error("同步账户数据失败", e);
            return R.error("同步账户数据失败");
        }
    }

    @GetMapping("/getUserListByOrgId/{orgId}")
    public List<User> getUserListByOrgId(@PathVariable("orgId") String orgId){
        try{
            List<User> list = sysUserService.getUserListByOrgId(orgId);
            return list;
        }catch (Exception e){
            e.printStackTrace();
            log.error("获取失败",e);
            return new ArrayList<User>();
        }

    }

    @PostMapping("/selectByStaffId")
    public User selectByStaffId(@RequestBody String staffId){
        return sysUserService.selectByStaffId(staffId);
    }

    /**
     * 根据userName查询用户
     *
     * @param userName String
     * @return 用户
     */
    @PostMapping("/selectByUserName")
    public User selectByUserName(@RequestBody String userName){
        return sysUserService.selectByUserName(userName);
    }

    @UserOperateLog(module = "系统功能", methods = "changeUsersDept", description = "调整部门")
    @PostMapping("/changeUsersDept")
    public R changeUsersDept(@RequestBody UserDeptChange param) {
        try {
            sysUserService.changeUsersDept(param, UserUtil.getUser());
            return R.ok();
        } catch (Exception e) {
            log.error("调整用户部门失败", e);
            return R.error("调整用户部门失败");
        }
    }

    /**
     * 内部处理数据用，请注掉
     * @param userId
     * @return
     */
    /*@UserOperateLog(module = "系统功能", methods = "resetPasswordBath", description = "批量重置密码")
    @GetMapping("/resetPasswordBath")
    public R resetPasswordBath() {
        try {
            String password = sysUserService.resetPasswordBath();
            return R.ok().put("random", password);
        } catch (Exception e) {
            log.error("重置密码失败", e);
            return R.error("重置密码失败！");
        }
    }*/
    
    /**
     * 仅查询用户基本信息
     * @param userId 用户id
     * @return 用户对象
     */
    @GetMapping("/getUserOnly/{userId}")
    public User getUserOnly(@PathVariable("userId") String userId){
        return sysUserService.selectById(userId);
}
    
    /**
     * 根据id查询用户
     * @param userIds
     * @return
     */
    @PostMapping("/getUsersOnly")
    public List<User> getUsersOnly(@RequestBody List<String> userIds){
        return sysUserService.getUsersOnly(userIds);
    }
    
    @GetMapping("/resetPasswordSimple/{userId}")
    public R resetPasswordSimple(@PathVariable("userId") String userId){
        try {
            String password = sysUserService.resetPasswordSimple(userId);
            return R.ok("已将密码重置为初始密码");
        } catch (Exception e) {
            log.error("重置密码失败", e);
            return R.error("重置密码失败！");
        }
    }
    
    /**
     * 系统管理员查用户
     * @param params {username:,staffName:,enterpriseName:,orgCode:,orgName,staffId:,status:}
     * @return 分页数据
     */
    @GetMapping("/listAdmin")
	@RequiresPermissions("sys:userAdmin:list")
    public R listAdmin(@RequestParam Map<String, Object> params) {
        //
        UserVO userVO = UserUtil.getUser();
        PageUtils page = sysUserService.queryPageAdmin(params, userVO);
        
        return R.ok().put("page", page);
    }
    
    /**
     * 将状态为删除的用恢复回来变成状态正常的
     * @param id 用户id
     * @return 结果
     */
    @GetMapping("/rollbackUser/{id}")
    @RequiresPermissions("sys:userAdmin:rollback")
    public R rollbackUser(@PathVariable("id") String id) {
        try {
            sysUserService.rollbackUser(id);
            return R.ok();
        } catch (Exception e) {
            log.error("找回用户失败", e);
            return R.error("找回用户失败！");
        }
    }
    
    /**
     * 物理删除用户，慎用
     * @param id 用户id
     * @return 结果
     */
    @GetMapping("/deletePhysical/{id}")
    @RequiresPermissions("sys:userAdmin:delete")
    public R deletePhysical(@PathVariable("id") String id) {
        try {
            UserVO userVO = UserUtil.getUser();
            if (Constant.SUPER_ADMIN.equals(id)) {
                return R.error("系统管理员不能删除");
            }
            if (userVO.getId().equals(id)) {
                return R.error("当前用户不能删除");
            }
            sysUserService.deletePhysical(id);
            return R.ok();
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return R.error("删除用户失败！");
        }
    }
    
    @GetMapping("/portalUserDeal/{myDate}")
    public R portalUserDeal(@PathVariable("myDate") long myDate) {
        try {
            //处理入库后的数据
            log.info("开始执行用户数据更新................");
            long start1 = System.currentTimeMillis();
            portalUserService.userDeal(myDate);
            long end1 = System.currentTimeMillis();
            log.info("执行用户数据更新完成，共用时" + (end1-start1)/1000 + "秒................");
            return R.ok();
        } catch (Exception e) {
            log.error("执行用户数据更新失败", e);
            return R.error("执行用户数据更新失败！");
        }
    }
    
    /**
     * 查询管辖某个机构的人员
     * @param orgId 机构编码
     * @return 人员信息
     */
    @GetMapping("/queryMngUsersByOrgId/{orgId}")
    public R queryMngUsersByOrgId(@PathVariable("orgId") String orgId) {
        //特殊情况，关系还在但用户已被删除的问题
        // List<UserMngOrg> list = sysUserMngOrgService.getListByOrgId(orgId);
        List<Map<String,Object>> listUsers = sysUserMngOrgService.getMngUsersListByOrgId(orgId);
        /*List<Map<String,Object>> listRe = list.stream().map(m -> {
            Map<String,Object> map = new HashMap<>();
            map.put("userId", m.getUserId());
            User user = sysUserService.selectById(m.getUserId());
            map.put("username", user.getUsername());
            map.put("staffName", user.getStaffName());
            return map;
        }).collect(Collectors.toList());*/
        return R.ok().put("list", listUsers);
    }
}
